package cn.good.yan.sf.t7;

import java.util.Iterator;

/**
 * 7 栈 - 基于 数组实现
 *
 * @author shengren.yan
 * @create 2024-07-27
 */
public class ArrayStack<E> implements Stack<E>, Iterable<E> {

    E[] arr;
    int size = 0;

    @SuppressWarnings("all")
    public ArrayStack(int size) {
        arr = (E[]) new Object[size];
    }

    @Override
    public boolean push(E e) {
        if (isFull()) {
            return false;
        }
        arr[size] = e;
        size++;
        return true;
    }

    @Override
    public E pol() {
        if (isEmpty()) {
            return null;
        }
        E e = arr[size - 1];
        size--;
        return e;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        E e = arr[size - 1];
        return e;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == arr.length;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int n = size;

            @Override
            public boolean hasNext() {
                return n > 0;
            }

            @Override
            public E next() {
                E e = arr[n - 1];
                n--;
                return e;
            }
        };
    }

    public static void main(String[] args) {
        ArrayStack<Integer> q = new ArrayStack<>(5);
        System.out.println("移除元素：" + q.pol());
        System.out.println("获取头元素：" + q.peek());
        System.out.println("添加元素：" + q.push(1));
        System.out.println("添加元素：" + q.push(2));
        System.out.println("添加元素：" + q.push(3));
        System.out.println("添加元素：" + q.push(4));
        System.out.println("添加元素：" + q.push(5));
        System.out.println("添加元素：" + q.push(6));
        System.out.println("添加元素：" + q.push(7));
        System.out.println("--------------");
        for (Integer i : q) {
            System.out.println(i);
        }
        System.out.println("获取头元素：" + q.peek());
        System.out.println("移除元素：" + q.pol());
        System.out.println("移除元素：" + q.pol());
        System.out.println("移除元素：" + q.pol());
        System.out.println("移除元素：" + q.pol());
        System.out.println("--------------");
        for (Integer i : q) {
            System.out.println(i);
        }
        System.out.println("--------------");
    }

}
